<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\Logs;
use think\App;
use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use think\response\Json;

class BusinessAdmin extends Base
{

    //主键
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\BusinessAdmin';

    protected $append = ['business'];

    public function index()
    {
        return $this->setTable();
    }

    //自动构建table,按需修改
    public function setTable()
    {
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'business', 'title' => '商户名称', 'templet' => '<div>{{d.business.title}}</div>'])
            ->addRow(['field' => 'mobile', 'title' => '手机号', 'width' => 200])
            ->addRow(['field' => 'admin_name', 'title' => '账号'])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons([
                'login' => ['title' => '登录商家后台', 'type' => 'login', 'url' => url('BusinessAdmin/login')->build()],
            ])
            ->addSwitchTool([['name' => 'status', 'pk' => 'id', 'text' => '开启|关闭']])
            ->setSearch($this->setSearch())
            ->addJsUrl(['business'])
            ->fetch();
    }

    //自动构建Search，按需修改
    public function setSearch()
    {
        return TableFront::getInstance()
            ->setSearch(['admin_name', '账号', 'input', '', '', '', 'like']);

    }

    public function login($id): Json
    {
        try {
            $businessAdmin = $this->model::find($id);
            $businessAdmin->last_time = time();
            $businessAdmin->save();
            session('business_admin_id', $businessAdmin['id']);
            session('business_password_token', md5($businessAdmin->password));
            Logs::adds('商户管理员【' . $businessAdmin['admin_name'] . '】登录了系统');
            return json(['code' => 1, 'msg' => '登录成功，正在跳转...']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

}
